package com.xinruke.hostels.dailymanage.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.common.cache.ManageUserCache;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.exception.BizException;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.YwZhengjianxinxi;
import com.xinruke.hostels.common.po.constants.YwZhengjianxinxiConstants;
import com.xinruke.hostels.common.util.CustomSecurity;
import com.xinruke.hostels.common.vo.ErrorEnum;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.dailymanage.interfaces.dto.guest.*;
import com.xinruke.hostels.dailymanage.mapper.YwZhengjianxinxiMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.weekend.Weekend;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yutaipu
 */
@Service
public class GuestService {

    @Autowired
    private YwZhengjianxinxiMapper ywZhengjianxinxiMapper;

    @Autowired
    private ManageUserCache manageUserCache;

    /**
     * 保存宾客信息，有则更新，无则新增
     *
     * @param zhengjianxinxi
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveGuest(YwZhengjianxinxi zhengjianxinxi) {
        QueryConditions queryConditions = new QueryConditions();
        queryConditions.addCondition("jiudianId", EConditionOperator.EQULS, zhengjianxinxi.getJiudianId());
        queryConditions.addCondition("zhengjianleixing", EConditionOperator.EQULS, zhengjianxinxi.getZhengjianleixing());
        queryConditions.addCondition("zhengjianhao", EConditionOperator.EQULS, zhengjianxinxi.getZhengjianhao());
        queryConditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        MyExample myExample = new MyExample(YwZhengjianxinxi.class, queryConditions);
        List<YwZhengjianxinxi> zhengjianxinxiList = ywZhengjianxinxiMapper.selectByExample(myExample);
        if (CollectionUtils.isEmpty(zhengjianxinxiList)) {
            zhengjianxinxi.setChuangjianshijian(new Date());
            zhengjianxinxi.setGengxinshijian(new Date());
            zhengjianxinxi.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
            zhengjianxinxi.setZhuangtai(YwZhengjianxinxiConstants.ZHUANGTAI_QIYONG);

            int ret = ywZhengjianxinxiMapper.insertSelective(zhengjianxinxi);
            if (ret > 0) {
                return zhengjianxinxi.getId();
            } else {
                return ret;
            }
        } else {
            YwZhengjianxinxi zhengjianxinxi0 = zhengjianxinxiList.get(0);
            zhengjianxinxi0.setShoujihao(zhengjianxinxi.getShoujihao());
            zhengjianxinxi0.setXingming(zhengjianxinxi.getXingming());
            zhengjianxinxi0.setZhengjianhao(zhengjianxinxi.getZhengjianhao());
            zhengjianxinxi0.setZhengjianleixing(zhengjianxinxi.getZhengjianleixing());
            zhengjianxinxi0.setJiudianId(zhengjianxinxi.getJiudianId());
            ywZhengjianxinxiMapper.updateByPrimaryKeySelective(zhengjianxinxi0);
            return zhengjianxinxi0.getId();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVO add(GuestAddDTO params) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }

        YwZhengjianxinxi add = new YwZhengjianxinxi();
        BeanUtils.copyProperties(params, add);
        add.setJiudianId(manageUserCache.getJiudianId());
        add.setZhuangtai(YwZhengjianxinxiConstants.ZHUANGTAI_QIYONG);
        add.setChuangjianshijian(new Date());
        add.setGengxinshijian(new Date());
        add.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
        int insert = ywZhengjianxinxiMapper.insertSelective(add);
        if (insert == 0) {
            return ResultVO.fail();
        }
        return resultVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVO modify(GuestModifyDTO params) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwZhengjianxinxi modify = new YwZhengjianxinxi();
        BeanUtils.copyProperties(params, modify);
        modify.setGengxinshijian(new Date());
        int count = ywZhengjianxinxiMapper.updateByPrimaryKeySelective(modify);
        if (count == 0) {
            return ResultVO.fail();
        }
        return resultVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVO delete(GuestDeleteDTO params) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwZhengjianxinxi delete = new YwZhengjianxinxi();
        BeanUtils.copyProperties(params, delete);
        delete.setGengxinshijian(new Date());
        delete.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        int insert = ywZhengjianxinxiMapper.updateByPrimaryKeySelective(delete);
        if (insert == 0) {
            return ResultVO.fail();
        }
        return resultVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVO updateStatus(Integer id, Byte status) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwZhengjianxinxi update = new YwZhengjianxinxi();
        update.setId(id);
        update.setZhuangtai(status);
        update.setGengxinshijian(new Date());
        int insert = ywZhengjianxinxiMapper.updateByPrimaryKeySelective(update);
        if (insert == 0) {
            return ResultVO.fail();
        }
        return resultVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVO updateStatus(List<Integer> idList, Byte status) {

        for (Integer id : idList) {
            ResultVO resultVO = updateStatus(id, status);
            if (resultVO.getCode() != ResultVO.SUCCESS) {
                throw new BizException(ErrorEnum.ERROR_50001);
            }
        }
        return ResultVO.success();
    }

    public ResultVO<RowsDataVO<GuestQueryResultDTO>> list(GuestQueryListDTO params) {
        RowsDataVO<GuestQueryResultDTO> dataVO = new RowsDataVO<>();

        params.setZhengjianhao(CustomSecurity.encodeIDCard(params.getZhengjianhao()));

        QueryConditions conditions = new QueryConditions();
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        conditions.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        conditions.addCondition("zhuangtai", EConditionOperator.EQULS, params.getZhuangtai());
        conditions.addCondition("shoujihao", EConditionOperator.LIKE, params.getShoujihao());
        conditions.addCondition("xingming", EConditionOperator.LIKE, params.getXingming());
        conditions.addCondition("zhengjianleixing", EConditionOperator.EQULS, params.getZhengjianleixing());
        conditions.addCondition("zhengjianhao", EConditionOperator.LIKE, params.getZhengjianhao());

        MyExample example = new MyExample(YwZhengjianxinxi.class, conditions, params.getOrderFields());
        Page<YwZhengjianxinxi> page = PageHelper.startPage(params.getPageNo(), params.getPageSize());
        List<YwZhengjianxinxi> list = ywZhengjianxinxiMapper.selectByExample(example);

        List<GuestQueryResultDTO> dtoList = list.stream().map(n -> {
            GuestQueryResultDTO dto = new GuestQueryResultDTO();
            BeanUtils.copyProperties(n, dto);
            return dto;
        }).collect(Collectors.toList());

        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(dtoList);
        return ResultVO.success("查询成功", dataVO);
    }

    public ResultVO<GuestQueryResultDTO> detail(GuestDetailDTO params) {
        GuestQueryResultDTO dto = new GuestQueryResultDTO();
        YwZhengjianxinxi detail = ywZhengjianxinxiMapper.selectByPrimaryKey(params.getId());

        if (null == detail) {
            return ResultVO.fail("没有此记录");
        }
        BeanUtils.copyProperties(detail, dto);
        return ResultVO.success("获取详情成功", dto);
    }

    public ResultVO<RowsDataVO<GuestLikeQueryResultDTO>> likeQueryList(GuestLikeQueryDTO guestLikeQueryDTO) {
        ResultVO<RowsDataVO<GuestLikeQueryResultDTO>> resultVO = ResultVO.success();

        QueryConditions andConditions = new QueryConditions();
        andConditions.addCondition("jiudianId", EConditionOperator.EQULS, guestLikeQueryDTO.getJiudianId());
        andConditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        MyExample myExample = new MyExample(YwZhengjianxinxi.class, andConditions);

        QueryConditions orConditions = new QueryConditions();
        orConditions.addCondition("xingming", EConditionOperator.LIKE, guestLikeQueryDTO.getNameNum());
        orConditions.addCondition("zhengjianhao", EConditionOperator.LIKE, CustomSecurity.encodeIDCard(guestLikeQueryDTO.getNameNum()));
        Weekend orWeekend = myExample.createOrWeekend(YwZhengjianxinxi.class, orConditions);
        orWeekend.and(myExample.getOredCriteria().get(0));

        Page<YwZhengjianxinxi> page = PageHelper.startPage(guestLikeQueryDTO.getPageNo(), guestLikeQueryDTO.getPageSize());
        List<YwZhengjianxinxi> ywZhengjianxinxis = ywZhengjianxinxiMapper.selectByExample(orWeekend);

        List<GuestLikeQueryResultDTO> collect = ywZhengjianxinxis.stream().map(e -> {
            GuestLikeQueryResultDTO guestLikeQueryResultDTO = new GuestLikeQueryResultDTO();
            BeanUtils.copyProperties(e, guestLikeQueryResultDTO);
            return guestLikeQueryResultDTO;
        }).collect(Collectors.toList());

        RowsDataVO<GuestLikeQueryResultDTO> rowsDataVO = new RowsDataVO<>();
        rowsDataVO.setPageNo(page.getPageNum());
        rowsDataVO.setTotalRecords(page.getTotal());
        rowsDataVO.setTotalPages(page.getPages());
        rowsDataVO.setRows(collect);
        resultVO.setData(rowsDataVO);
        return resultVO;
    }
}
